package com.itheima.health.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.health.dto.RoleDto;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.mapper.RoleMapper;
import com.itheima.health.pojo.Role;
import com.itheima.health.service.PermissionService;
import com.itheima.health.service.RoleService;
import com.itheima.health.vo.RoleVO;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private PermissionService permissionService;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Page pageData=null;
        QueryWrapper<Role> wrapper=new QueryWrapper<>();
        if (queryPageBean.getQueryString()==null){
            pageData=page(new Page<>(queryPageBean.getCurrentPage(),queryPageBean.getPageSize()));
        }else {
            wrapper.like("NAME",queryPageBean.getQueryString());
            pageData=page(new Page<>(queryPageBean.getCurrentPage(),queryPageBean.getPageSize()),wrapper);
        }

        return new PageResult(pageData.getTotal(),pageData.getRecords());
    }

    @Override
    public Boolean saveUpdate(RoleDto roleDto) {
        Integer rid = roleDto.getId();
        if (rid!=null){
            //更新操作，先删除根据rid删除中间表数据  中间表  两个中间表
            baseMapper.deletePidByRid(rid);
            baseMapper.deleteMidByRid(rid);
        }
        //更新或新增操作  角色表
        boolean flag = saveOrUpdate(roleDto);
        rid=roleDto.getId();
        Integer[] pIds =roleDto.getPermissionIds();

        //遍历操作，根据角色id往中间表添加权限id  中间表
        if (pIds!=null&&pIds.length>0){
            for (Integer pid : pIds) {
                baseMapper.insertPidByRid(rid,pid);
            }
        }

        //遍历操作，根据角色id往中间表添加菜单id  中间表
        Integer[] mIds = roleDto.getMenuIds();
        if (mIds!=null&&mIds.length>0){
            for (Integer mid : mIds) {
                baseMapper.insertMidByRid(rid,mid);
            }
        }
        return flag;
    }

    @Override
    public RoleVO findPidByRid(Integer rid) {
        //通过角色id查询角色信息  角色表
        RoleVO roleVO=baseMapper.findByRid(rid);
        //查询所有权限信息放到集合中  权限表
        roleVO.setPermissionsList(permissionService.list());
        //根据角色id查询所拥有的权限id数组  中间表
        roleVO.setPermissionIds(baseMapper.findPids(rid));
        //根据角色id查询菜单数组   中间表
        roleVO.setMenuIds(baseMapper.findMids(rid));
        return roleVO;
    }

    @Override
    public boolean deleteById(Integer id) {
        return baseMapper.deleteById(id)==1;
    }
}
